<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Express;
use app\common\model\Cart;
use app\common\model\goods\Review;
use app\common\model\order\Goods;
use app\common\model\order\Order as OrderOrder;
use fast\Random;
use think\Db;
use think\Log;
use think\Queue;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * @Author LK
     * @ApiTitle (下单预览)
     * @ApiMethod (POST)
     * @ApiParams (name="ids", type="string", required=true, sample="", description="购物id|商品id")
     * @ApiParams (name="product_id", type="integer", required=true, sample="", description="规格id（立即购买必填）")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="数量（立即购买必填）")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=购物购买，2=立即购买")
     * @ApiParams (name="address_id", type="integer", required=true, sample="", description="地址ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function yu_order()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        try {
            if ($type == 2) {
                $param = [
                    'num' => $num,
                    'user_id' => $uid,
                    'goods_id' => $ids,
                    'product_id' => $product_id,
                ];
                $cart_ids = Cart::add($param, 1, 1, 2);
            } else {
                $cart_ids = $ids;
            }
            $goods = OrderOrder::yuOrder($cart_ids, $uid, $address_id);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', $goods);
    }
    /**
     * @Author LK
     * @ApiTitle (再次购买)
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="integer", required=true, sample="", description="order_id")
     * @ApiParams (name="address_id", type="integer", required=true, sample="", description="address_id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function repurchase()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        try {
            $list = Goods::where('order_id', $order_id)->field('goods_id,product_id,goods_num')->select();
            $cart_ids = [];
            foreach ($list as $key => $v) {
                $param = [
                    'num' => $v->goods_num,
                    'user_id' => $uid,
                    'goods_id' => $v->goods_id,
                    'product_id' => $v->product_id,
                ];
                array_push($cart_ids, Cart::add($param, 1, 0, 2));
            }
            $goods = OrderOrder::yuOrder($cart_ids, $uid, $address_id);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', $goods);
    }
    /**
     * @Author LK
     * @ApiTitle (订单下单)
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_order()
    {
        $param = request()->param();
        try {
            $orderid = OrderOrder::addOrder($param);
            if ($orderid) {
                Cart::whereIn('id', $param['cart_ids'])->where('user_id', $this->auth->id)->delete();
                queue('app\\common\\job\\CancelOrder@cancel', $orderid, 900, '1275cancelorder');
                // Queue::later(30,'\app\common\job\CancelOrder@cancel',$orderid,'1275cancelorder');
                Log::error('开始发送消息：' . json_encode($orderid));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('', $orderid);
    }
    /**
     * @Author LK
     * @ApiTitle (订单列表)
     * @ApiMethod (GET)
     * @ApiParams (name="order_status", type="string", required=true, sample="", description="all=全部,0=待支付,10=待发货,20=待收货,30=待评价,40=已完成")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_list()
    {
        $param = request()->param();
        extract($param);
        if (!isset($order_status)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $order = new OrderOrder();
        if ($order_status != 'all') {
            $order->where('order_status', $order_status);
        }
        $lists = $order->with(['ordergoods'])->where('user_id', $uid)->where('order_status', '<>', '-1')->order('id desc')->paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @ApiTitle (订单详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        $data = OrderOrder::get($id, ['ordergoods']);
        $this->success('', $data);
    }

    /**
     * @Author LK
     * @ApiTitle (取消订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_order()
    {
        $param = request()->param();
        extract($param);
        $data = OrderOrder::get($id);
        if (!$data) {
            $this->error('订单不存在');
        }
        if ($data->order_status != '0') {
            $this->error('订单状态错误');
        }
        $data->order_status = '-1';
        $res = $data->save();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
    /**
     * @Author LK
     * @ApiTitle (查看物流)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function logistics()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        $express = new Express($order);
        $wuliu = $express->getOrderTracesByJson();
        $wuliu['express_name'] = Db::name('express')->where('customer', $order['express_com'])->value('name');
        $wuliu['address'] = $order['address'];
        // $wuliu['city'] = $order['city'];
        $wuliu['nu'] = $order['express_no'];
        $this->success('', $wuliu);
    }
    /**
     * @Author LK
     * @ApiTitle (确认收货)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function confirm_order()
    {
        $param = request()->param();
        extract($param);
        $data = OrderOrder::get($id);
        if (!$data) {
            $this->error('订单不存在');
        }
        if ($data->order_status != '20') {
            $this->error('订单状态错误');
        }
        $data->order_status = '30';
        $data->taketime = time();
        $res = $data->save();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
    /**
     * @Author LK
     * @ApiTitle (评价)
     * @ApiMethod (GET)
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="integer", required=true, sample="", description="订单ID")
     * @ApiParams (name="data", type="string", required=true, sample="[
     * {goods_id:1,description:'撒大撒大撒大撒',images:'1.png',star:1,product_id:1},
     * {goods_id:1,description:'撒大撒大撒大撒',images:'1.png',star:1,product_id:1}
     * ]", description="评价商品信息")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function evaluate()
    {
        $param = request()->param();
        extract($param);
        Db::startTrans();
        try {
            foreach ($data as $v) {
                $data = [
                    'user_id' => $this->auth->id,
                    'goods_id' => $v['goods_id'],
                    'description' => $v['description'],
                    'images' => $v['images'],
                    'order_id' => $order_id,
                    'star' => $v['star'],
                    'product_id' => $v['product_id'],
                ];
                Review::create($data);
            }
            OrderOrder::where('id', $order_id)->update(['order_status' => '40']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('错误：' . $e->getMessage() . '------' . $e->getLine());
        }
        $this->success('评价成功');
    }
}
